from django import template
from django.core.urlresolvers import reverse
from urllib import quote
import random
from couchdbkit import client
from django.conf import settings


register = template.Library()

CLOUD_SIZE = 40

server=client.Server(settings.COUCHDB_HOST)
db = server[settings.COUCHDB_DATABASE_NAME]


def make_tags(topics):
	for topic in topics:
		si = random.random() #si = size indicator
		yield u'<div class="%(size)s"><a href="/%(url)s">%(name)s</a></div>' % {
			'size': (u' small' if si < .1 else
					 u'' if si < .5 else
					 u' big' if si < .85 else
					 u' verybig'),
			'url': topic['id'],
			'name': topic['name']}


@register.simple_tag
def topics_cloud():
	topic_ids = [row['key'] for row in db.view('sti/topics').all() if 'topics/' in row['key']]
	indices = set([random.randint(0,len(topic_ids)-1) for i in range(CLOUD_SIZE)])
	selected_topics = [db.view('sti/topics',key=topic_ids[i]).first() for i in indices]
	selected_topics = [t['value'] for t in selected_topics if t]

	return u'\n'.join(make_tags(selected_topics))

